package thread;

import java.util.concurrent.locks.ReentrantLock;

/**
 * 解决线程安全的方式三：Lock锁     ---JDK5.0新增
 *
 * @author Bboy Dday
 * @create 2020:06:15--13:53
 */

class Window6 implements Runnable{
    private int ticket = 100;

    //1. 实例化 ReentrantLock
    private ReentrantLock lock = new ReentrantLock();//括号中可以是无参或者true,false，如果不写就是false，true表示有顺序进入

    @Override
    public void run() {

        while ( true ) {

            try {

                //2. 调用lock()方法
                lock.lock();

                if (ticket > 0) {

                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                    System.out.println(Thread.currentThread().getName() + "售票：" + ticket);
                    ticket--;
                }else break;
            }finally {
                //3. 解锁方法
                lock.unlock();
            }


        }

    }
}

public class LockTest {
    public static void main(String[] args) {
        Window6 w = new Window6();

        Thread t1 = new Thread(w);
        Thread t2 = new Thread(w);
        Thread t3 = new Thread(w);

        t1.setName( "窗口1" );
        t2.setName( "窗口2" );
        t3.setName( "窗口3" );

        t1.start();
        t2.start();
        t3.start();

    }
}

